package com.leyou.mq;

import com.leyou.exception.LyException;
import com.leyou.utils.RegexUtils;
import com.leyou.utils.SmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @author ：qcq
 * @date ：Created in 2020/12/16 20:29
 * @description：
 */
@Slf4j
@Component
public class MessageListener {

    @Autowired
    private SmsUtils smsUtils;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "sms.verify.code.queue", durable = "true"),
            exchange = @Exchange(name = "ly.sms.exchange", type = ExchangeTypes.TOPIC),
            key = "sms.verify.code"
    ))
    public void listenVerifyCodeMessage(Map<String, String> map) {
        if (CollectionUtils.isEmpty(map)) {
            return;
        }
        String phone = map.get("phone");
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "手机号码格式错误");
        }
        String code = map.get("code");
        if (!RegexUtils.isCodeValid(code)) {
            throw new LyException(400, "验证码有误");
        }
        try {
            smsUtils.sendVerifyCode(phone, code);
        } catch (Exception e) {
            log.error("【SMS服务】短信验证码发送失败", e);
        }
    }
}
